package com.leesche.zcsp.node.web.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.leesche.zcsp.node.app.v1.timer.TokenCacheTimer;
import com.leesche.zcsp.node.utils.security.QEncodeUtil;
import com.leesche.zcsp.node.utils.web.SessionManager;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.dao.PubDiscountDao;
import com.leesche.zcsp.node.web.dao.SysRoleDao;
import com.leesche.zcsp.node.web.dao.SysUserRoleDao;
import com.leesche.zcsp.node.web.model.*;
import com.leesche.zcsp.node.web.service.PubDiscountService;
import com.leesche.zcsp.node.web.service.SysUserRoleService;
import com.leesche.zcsp.node.web.service.impl.data.read.PubDiscountDto;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysModuleCondition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.leesche.zcsp.node.web.dao.SysUserDao;
import com.leesche.zcsp.node.web.service.SysUserService;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysUserCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.SysUserDto;
import com.leesche.zcsp.node.web.vo.Principal;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 陈立勇
 * @version V1.0
 * @Title: SysUserServiceImpl.java
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @date 2016年9月18日 上午1:26:41
 */
@Service
@Transactional
public class SysUserServiceImpl
        extends
        BaseServiceImpl<SysUser, SysUserCriteria, SysUserDto, QuerySysUserCondition, Long>
        implements SysUserService {
    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    @Autowired
    private SysRoleDao sysRoleDao;

    @Autowired
    private PubDiscountService pubDiscountService;

    @Autowired
    public void setBaseDao(SysUserDao sysUserDao) {
        super.setBaseDao(sysUserDao);
    }

	/* (non-Javadoc)
     * @see com.leesche.zcsp.node.web.service.SysUserService#findSysUserByUsernameAndPassword(com.leesche.zcsp.node.web.service.impl.data.read.QuerySysUserCondition)
	 */
/*	@Override
	public Principal findSysUserByUsernameAndPassword(QuerySysUserCondition condition) {
		// TODO Auto-generated method stub
		return converToPrincipal(sysUserDao.selectSysUserByUsernameAndPassword(condition));
	}
	
	private  Principal  converToPrincipal(SysUser sysUser){
		if(sysUser!=null){
			 return new Principal(sysUser.getUserid(), sysUser.getUsername(), sysUser.getNtype(), sysUser.getOpenid());
		}
		return null;
	}*/

    @Override
    public SysUser findUserByUsername(SysUser sysUser) {
        // TODO Auto-generated method stub return null;
        return sysUserDao.selectSysUserByUsername(sysUser);
    }

    @Override
    public int addChildUsers(List<SysUser> childUsers) {
        // TODO Auto-generated method stub return 0;
        return sysUserDao.insertBatch(childUsers);
    }

    @Override
    public int changePassword(SysUser user) {
        // TODO Auto-generated method stub return 0;
        return sysUserDao.updateUserPasswordByUserID(user);
    }

    @Override
    public int changeTransferPassword(SysUser user) {
        // TODO Auto-generated method stub return 0;
        return sysUserDao.updateUserTransferPasswordByUserID(user);
    }

    @Override
    public List<SysUser> findChildUsers(SysUser parentUser) {
        // TODO Auto-generated method stub return null;
        return sysUserDao.selectByParentUserID(parentUser);
    }

    @Override
    public SysUser findLastUserByParentID(Long parentUserID) {
        // TODO Auto-generated method stub return null;
        return sysUserDao.selectLastChildUserByParentUserid(parentUserID);
    }

    @Override
    public List<SysUserDto> findChildUserByPrientIDAndRoleID(QuerySysUserCondition condition) {
        return sysUserDao.selectChildUserByParentIDAndRoleID(condition);
    }

    /*
        @Transactional(propagation = Propagation.NESTED, timeout = 1000, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    */
    @Override
    public SysUser createUser(SysUser user, PubDiscountService pubDiscountService) throws Exception {
        //创建商户信息
        int addResult = sysUserDao.insertSelective(user);
        if (addResult > 0) {
            //由于是在数据库生成了商户号，所以当商户生成后需持久化该商户信息
            SysUser parentUser = sysUserDao.selectByPrimaryKey(user.getUserid());
            String childUserBO = parentUser.getBusinessno() + "0";
            Long childParentID = parentUser.getUserid();
            int childState = parentUser.getState();
            int childNtype = parentUser.getNtype();
            Date childCreaterTime = parentUser.getCreatetime();
            Date childOutTime = parentUser.getOuttime();
            //创建子账户列表
            List<SysUser> childUsers = new ArrayList<SysUser>();
            //实例化三个子账户信息，并追加到子账户列表中
            for (int i = 1; i <= 3; i++) {
                SysUser childUser = new SysUser();
                childUser.setUsername(childUserBO + i);
                childUser.setBusinessno(childUserBO + i);
                childUser.setPuserid(childParentID);
                childUser.setAdminid(childParentID);
                childUser.setNtype(++childNtype);
                childUser.setState(childState);
                childUser.setRemark("系统自动分配的第" + i + "个子账户");
                childUser.setCreatetime(childCreaterTime);
                childUser.setOuttime(childOutTime);
                childUser.setPassword(QEncodeUtil
                        .md5Encrypt(Constants.NOTIC_DEFAULT_USER_PASSWORD));
                childUsers.add(childUser);
            }

            //批量添加子账户信息
            sysUserDao.insertBatch(childUsers);
            // 默认分配角色
            int setupResult = this.setupUserRoleBatch(parentUser);

            if (setupResult > 0) {
                // 生成默认设备套餐
                List<PubDiscount> pubDiscounts = new ArrayList<PubDiscount>();
                int[] numbers = {1, 5, 10, 20, 50, 100};
                for (int i = 0; i < numbers.length; i++) {
                    PubDiscount pubdiscount = new PubDiscount();
                    int number = numbers[i];
                    pubdiscount.setDiscountname(number + "元" + number + "币");
                    pubdiscount.setMoney(number);
                    pubdiscount.setCoin(number);
                    pubdiscount.setAdminid(parentUser.getUserid());
                    pubdiscount.setRemark("系统默认分配第" + (i + 1) + "个套餐");
                    pubDiscounts.add(pubdiscount);
                }

                pubDiscountService.addDefaultDiscount(pubDiscounts);

            }
            return parentUser;
        }
        return null;
    }

    @Override
    public int setupUserRoleBatch(SysUser parentUser) {
        List<SysUser> users = this.findChildUsers(parentUser);

        users.add(parentUser);

        List<SysRole> roles = sysRoleDao.selectByRoleNtypes(users);

        List<SysUserRole> sysUserRoles = new ArrayList<SysUserRole>();
        Date nowTime = new Date();

        for (SysRole sysRole : roles) {
            for (SysUser sysUser : users) {

                if (sysUser.getNtype() == sysRole.getNtype()
                        && sysRole.getIsdefault() == 1) {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserid(sysUser.getUserid());
                    sysUserRole.setRoleid(sysRole.getRoleid());
                    sysUserRole.setAdminid(parentUser.getUserid());
                    sysUserRole.setCreatetime(nowTime);
                    sysUserRoles.add(sysUserRole);

                }
            }
        }

        return sysUserRoleDao.insertBatch(sysUserRoles);
    }

    @Override
    public Integer countUserByCondition(QuerySysUserCondition condition) {
        return sysUserDao.countUserByCondition(condition);
    }

    @Override
    public SysUser addUserInfo(SysUser user) throws Exception {
        //增加商户
        int result = sysUserDao.insertSelective(user);
        if (result > 0) {
            //由于是在数据库生成了商户号，所以当商户生成后需持久化该商户信息
            Long userid = user.getUserid();
            user = sysUserDao.selectByPrimaryKey(userid);
            String childUserBO = user.getBusinessno() + "0";
            int childState = user.getState();
            int childNtype = user.getNtype();
            Date childCreaterTime = user.getCreatetime();
            Date childOutTime = user.getOuttime();
            //创建子账户列表
            List<SysUser> childUsers = new ArrayList<SysUser>();
            //实例化三个子账户信息，并追加到子账户列表中
            for (int i = 1; i <= 3; i++) {
                SysUser childUser = new SysUser();
                childUser.setUsername(childUserBO + i);
                childUser.setBusinessno(childUserBO + i);
                childUser.setPuserid(userid);
                childUser.setAdminid(userid);
                childUser.setNtype(++childNtype);
                childUser.setState(childState);
                childUser.setRemark("系统自动分配的第" + i + "个子账户");
                childUser.setCreatetime(childCreaterTime);
                childUser.setOuttime(childOutTime);
                childUser.setPassword(QEncodeUtil.md5Encrypt(Constants.NOTIC_DEFAULT_USER_PASSWORD));
                childUsers.add(childUser);
            }

            // 生成默认设备套餐
            List<PubDiscount> pubDiscounts = new ArrayList<PubDiscount>();
            int[] numbers = {1, 5, 10, 20, 50, 100};
            for (int i = 0; i < numbers.length; i++) {
                PubDiscount pubdiscount = new PubDiscount();
                int number = numbers[i];
                pubdiscount.setDiscountname(number + "元" + number + "币");
                pubdiscount.setMoney(number);
                pubdiscount.setCoin(number);
                pubdiscount.setAdminid(userid);
                pubdiscount.setRemark("系统默认分配第" + (i + 1) + "个套餐");
                pubDiscounts.add(pubdiscount);
            }

            //批量添加子账户信息
            sysUserDao.insertBatch(childUsers);
            //添加设备套餐
            pubDiscountService.addDefaultDiscount(pubDiscounts);

            return user;

        }
        return null;
    }


    @Override
    public void saveLoginState(SysUser sysUser, List<Long> userModules,Integer loginType) {

        String principalName = sysUser.getBusinessno() != null ? sysUser
                .getBusinessno() : sysUser.getUsername();

        Principal principal = new Principal(sysUser.getUserid(), sysUser.getPuserid(), principalName,
                sysUser.getBusinessno(), sysUser.getNtype(),sysUser.getOpenid(), loginType,
                sysUser.getShortcode());
        principal.setModuleIds(userModules);

        SessionManager.setSessionAttribute(Constants.LOGIN_CURRENT_USER, principal);
    }

    @Override
    public void saveLoginState(SysUser sysUser, List<Long> userModules,Integer loginType,String usertoken) {

        String principalName = sysUser.getBusinessno() != null ? sysUser
                .getBusinessno() : sysUser.getUsername();

        Principal principal = new Principal(sysUser.getUserid(),
                sysUser.getPuserid(), principalName,
                sysUser.getBusinessno(), sysUser.getNtype(),
                sysUser.getOpenid(),usertoken, loginType,sysUser.getShortcode());
        principal.setModuleIds(userModules);

        //增加用户权限到缓存中去
        TokenCacheTimer.addUserPrincipal(usertoken,principal);
    }
}
